package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.Vo.VoteRecordVo;
import com.example.educationalsystem.entity.Vo.VoteVo;
import com.example.educationalsystem.entity.Vote;
import com.example.educationalsystem.entity.VoteRecord;
import com.example.educationalsystem.service.IVoteRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-26
 */
@RestController
@Api(value = "/voteRecord",tags = "投票记录信息管理")
@RequestMapping("/voteRecord")
public class VoteRecordController {

    @Autowired
    private IVoteRecordService iVoteRecordService;


    @GetMapping("/getVoteRecordPage")
    @ApiOperation(value = "获取投票记录分页信息",notes = "获取投票记录分页信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getVoteRecordPage(
            @RequestParam(value = "size", defaultValue = "10") long size,
            @RequestParam(value = "current", defaultValue = "1") long current,
            String studentId,String courseId
    )
    {
        ResponseJson responseJson=new ResponseJson();
        Page<VoteRecordVo> page=new Page<>(current,size);
        QueryWrapper<VoteRecordVo> queryWrapper=new QueryWrapper<>();
        if(studentId==null&&courseId==null)
        {
            queryWrapper=null;
        }

        Page<VoteRecordVo> VoteRecordVoPage=iVoteRecordService.getVoteRecordPage(page,queryWrapper);
        System.out.println(VoteRecordVoPage.toString());
        if(VoteRecordVoPage!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(VoteRecordVoPage);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无信息！");
        }
        return responseJson;

    }
    @ApiOperation(value = "导出所有投票记录信息",notes = "导出所有投票记录信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {

        try{
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
            EasyExcel.write(response.getOutputStream(), VoteRecordVo.class).sheet(tableName).doWrite(iVoteRecordService.getAllVoteRecord());
        }catch(Exception e)
        {
            response.reset();
        }


    }
    @ApiOperation(value = "导入投票记录信息",notes = "导入投票记录信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, VoteRecordVo.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() >=1) {
                for (int i = 0; i < list.size(); i++) {
                    VoteRecord voteRecord= (VoteRecord) list.get(i);
                    //使用mybatis-plus添加到数据库
                    iVoteRecordService.save(voteRecord);
                }
            }
            responseJson.setStatus(200);
            responseJson.setMsg("导入成功！");
        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg("导入失败！");
            e.printStackTrace();
        }

        return responseJson;
    }
    @GetMapping("/getAllVoteRecord")
    @ApiOperation(value = "获取所有投票记录信息",notes = "获取所有投票记录信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllVoteRecord()
    {
        ResponseJson responseJson=new ResponseJson();
        List<VoteRecordVo> VoteRecordlist=iVoteRecordService.getAllVoteRecord();
        if(VoteRecordlist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(VoteRecordlist);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，无得票信息！");
        }
        return responseJson;
    }

    @ApiOperation(value = "增加投票记录信息",notes = "增加一条投票记录信息记录")
    @PostMapping("/insertVoteRecord")
    @ResponseBody
    public ResponseJson insertVoteRecord(@RequestBody VoteRecord requestVoteRecord)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<VoteRecord> queryWrapper=new QueryWrapper<>();
        VoteRecord voteOne=iVoteRecordService.getBaseMapper().selectOne(queryWrapper.eq("student_id",requestVoteRecord.getStudentId()).eq("teacher_id",requestVoteRecord.getTeacherId()));
        if(voteOne==null)
        {
                    Boolean result=iVoteRecordService.save(requestVoteRecord);
                    if(result)
                    {
                        responseJson.setMsg("增加成功！");
                        responseJson.setStatus(200);
                        responseJson.setData(requestVoteRecord);

                    }
                    else
                    {
                        responseJson.setStatus(400);
                        responseJson.setMsg("增加失败！");
                    }
        }
        else
        {
            responseJson.setStatus(400);
            responseJson.setMsg("已投过票,请不要重复投票!");
        }
        return responseJson;
    }
    @ApiOperation(value = "批量删除投票记录信息",notes = "根据投票记录编号，删除多条投票记录信息")
    @DeleteMapping("/deleteVotes")
    @ResponseBody
    public  ResponseJson deleteVotes( @ApiParam(name = "Ids", value = "投票纪录IDs", required = true) @RequestParam String Ids)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result=iVoteRecordService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }

    @ApiOperation(value = "删除投票记录信息",notes = "根据ID，删除一条投票记录信息")
    @DeleteMapping("/deleteVoteRecord")
    @ResponseBody
    public  ResponseJson deleteVoteRecord( @ApiParam(name = "Id", value = "投票记录ID", required = true) @RequestParam String Id)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<VoteRecord> queryWrapper=new QueryWrapper<>();
        VoteRecord VoteRecordOne=iVoteRecordService.getBaseMapper().selectOne(queryWrapper.eq("id",Id));
        if(VoteRecordOne!=null)
        {
            int result=iVoteRecordService.getBaseMapper().deleteById(VoteRecordOne.getId());
            System.out.println(result);
            if(result==1)
            {
                responseJson.setData(VoteRecordOne);
                responseJson.setMsg("删除成功！");
                responseJson.setStatus(200);
            }
            else
            {
                responseJson.setMsg("删除失败");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("该投票记录信息不存在！");
        }
        return responseJson;

    }

    @ApiOperation(value = "更新投票记录信息",notes = "更新投票记录信息，必须填写ID")
    @PutMapping("/updateVoteRecord")
    @ResponseBody
    public ResponseJson updateVoteRecord(@RequestBody  VoteRecord resquestVoteRecord)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<VoteRecord> queryWrapper=new QueryWrapper<>();
        VoteRecord VoteRecordOne=iVoteRecordService.getBaseMapper().selectOne(queryWrapper.eq("id",resquestVoteRecord.getId()));
        if(VoteRecordOne!=null)
        {
            QueryWrapper<VoteRecord> queryWrapper1=new QueryWrapper<>();
            int result=iVoteRecordService.getBaseMapper().update(resquestVoteRecord,queryWrapper1.eq("id",resquestVoteRecord.getId()));
            if(result==1)
            {
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
                responseJson.setData(resquestVoteRecord);
            }
            else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setMsg("该投票记录信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;
    }


}

